package com.Jshop.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Description
 * 解决同源策略问题，设置允许的域名、请求方式、并拦截一切请求进行判断
 *
 * @Param
 * @return
 * @Date  2021/10/21
 **/
@Configuration
public class JCorsConfiguration {
    @Bean
    public CorsFilter corsFilter(){
        //添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //（服务器响应头返回允许的域）不要写*，否则cookie就无法使用了
        config.addAllowedOrigin("http://manage.jshop.com");
        config.addAllowedOrigin("http://www.jshop.com");
        //浏览器发起ajax需要指定withCredentials为true
        config.setAllowCredentials(true);
        //允许的请求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        //允许的头信息
        config.addAllowedHeader("*");

        //添加新的映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**",config);

        //返回新的CorsFilter
        return new CorsFilter(configSource);

    }
}
